package com.ruike.alisurface.ui.topupCard;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.ICCardUtils;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CardInfoBean;
import com.ruike.alisurface.bean.CardTopUpBean;
import com.ruike.alisurface.http.CardHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.adapter.CardTopupAdapter;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.ui.payPage.PayForQRCodeActivity;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020-03-29 029 下午 09:49
 * Description: 卡充值界面
 */
public class CardTopUpActivity extends BaseAty implements CardTopupAdapter.OnPriceSelectListener, ICCardUtils.OnICCardGetPwdListener {

    String cardNumber = ""; // 卡号
    float price = 0; // 充值金额

    CardTopupAdapter adapter;

    @BindView(R.id.cardTopUp_countDown_tv)
    TextView cardTopUp_countDown_tv;
    @BindView(R.id.cardTopUp_cardNumber_tv)
    TextView cardTopUpCardNumberTv;
    @BindView(R.id.cardTopUp_cardPrice_tv)
    TextView cardTopUpCardPriceTv;
    @BindView(R.id.cardTopUp_selectPrice_tv)
    TextView cardTopUpSelectPriceTv;
    @BindView(R.id.cardTopUp_priceList_recv)
    RecyclerView cardTopUpPriceListRecv;

    private boolean isCardRequest = true; // 获取到卡号之后是否需要请求

    @Override
    protected boolean getCanToOtherApp() {
        return true;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_card_top_up;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        ICCardUtils.setOnICCardGetPwdListener(this);

        List<Float> priceList = new ArrayList<>();

        priceList.add(BuildConfig.DEBUG ? 0.01f : 10.0f);
        priceList.add(30.0f);
        priceList.add(50.0f);
        priceList.add(100.0f);
        priceList.add(200.0f);

        adapter = new CardTopupAdapter(this, priceList);
        adapter.setOnPriceSelectListener(this);
        cardTopUpPriceListRecv.setLayoutManager(new GridLayoutManager(this, 3));
        cardTopUpPriceListRecv.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(120, cardTopUp_countDown_tv, MainActivity.class);
        ICCardUtils.getCardPwd(120_000); // 开始寻卡（开启刷卡设备）
//        ICCardUtils.getCardNumber();
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        ICCardUtils.stopGetCard();
    }

    @OnClick({R.id.cardTopUp_back_imgv, R.id.cardTopUp_submit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cardTopUp_back_imgv:
                startActivity(MainActivity.class, null);
                finish();
                break;
            case R.id.cardTopUp_submit_tv:
                if (cardNumber.isEmpty()) {
                    showErrorTip("请先刷卡");
                    return;
                }
                if (price <= 0) {
                    showErrorTip("请选择充值金额");
                    return;
                }
                MchApiHttp.createRechargeOrder(String.valueOf(price), cardNumber, this);
                break;
        }
    }

    /**
     * 获取块区回调监听
     *
     * @param cardBlocksData 解析出来之后的数据
     */
    @Override
    public void onResultCardPwd(String cardBlocksData) {
        // 第一次回调需要请求详情，防止一直回调一直请求
        if (isCardRequest) {
            isCardRequest = false;
            showProgressDialog("正在获取卡信息，请稍后...", false);
            CardHttp.getCardDetails(cardBlocksData, this);
        }
    }

    /**
     * 刷卡异常
     *
     * @param errorMsg 异常信息
     */
    @Override
    public void onCreditCardError(String errorMsg) {
        showErrorTip(errorMsg);
    }

    @Override
    public void onSelectPrice(float price) {
        this.price = price;
        cardTopUpSelectPriceTv.setText(new StringBuffer(" ￥").append(price));
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("card/get_card_details")) {
            CardInfoBean cardInfoBean = GsonUtils.json2Model(requestJsonStr, CardInfoBean.class);
            this.cardNumber = cardInfoBean.getData().getCard_no();
            cardTopUpCardNumberTv.setText(cardNumber);
            cardTopUpCardPriceTv.setText(new StringBuffer().append("￥").append(cardInfoBean.getData().getNow_balance()));
            return;
        }
        if (requestUrl.endsWith("Create_Recharge_Order")) {
            CardTopUpBean cardTopUpBean = GsonUtils.json2Model(requestJsonStr, CardTopUpBean.class);
            L.i(cardTopUpBean);
            Bundle bundle = new Bundle();
            bundle.putBoolean("isTopCarPay", true);
            bundle.putSerializable("cardTopUpBean", cardTopUpBean);
            startActivity(PayForQRCodeActivity.class, bundle);
            finish();
            return;
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        showErrorTip(errorMsg);
        if (requestUrl.endsWith("Card/QueryCardNo") || requestUrl.endsWith("card/get_card_details")) {
            new MyCountDownTimer(1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    isCardRequest = true;
                    ICCardUtils.getCardPwd(100_000);
                }
            }.start();
            return;
        }
    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
        super.onFailure(requestUrl, requestMsg);
    }
}
